'''
    Weibo Repost methods
'''

import types
import os
from WeiboClient import WeiboClient
from TimeParse import Time
from MySqlDBHandle import MySqlDBHandle
from WeiboAcc import WeiboAcc

class Repost(WeiboClient):
    mSQLStatement = "INSERT INTO Repost (Repost_id, Comment_Count, Repost_Count, Post_id, Weibo_id, Minute_id)\
    VALUES %s ON DUPLICATE KEY UPDATE Comment_Count = Values(Comment_Count),\
    Repost_Count = Values(Repost_Count);"
    mSQLValueStatement = "(%s, %s, %s, %s, %s, %s),"
    
    mAPI = 'statuses/repost_timeline'
    
    def __init__(self):
        WeiboClient.__init__(self)
        
    def _sendToDB(self, iPostId):
        assert(type(self.mRepostStatus) == types.ListType)
        for lSingleRepost in self.mRepostStatus:
            if lSingleRepost.has_key('deleted'):
                continue
            lWeiboInfo = lSingleRepost['user']
            lParams = {}
            lParams['id'] = lWeiboInfo['id']
            lParams['screen_name'] = lWeiboInfo['screen_name']
            lParams['followers_count'] = lWeiboInfo['followers_count']
            lWeoboAcc = WeiboAcc(lParams)
            lWeoboAcc.process()
            lTime = Time().getMinuteId(lSingleRepost['created_at'])
            lValueStatement = (self.mSQLValueStatement % (lSingleRepost['id'], lSingleRepost['comments_count'], lSingleRepost['reposts_count'],\
                                                         iPostId, lWeiboInfo['id'], lTime))
            lSQLStatement = self.mSQLStatement % lValueStatement[:len(lValueStatement) - 1]
            
            try:
                MySqlDBHandle.execSqlStatement(lSQLStatement)
            except Exception, e:
                print "Error in Repost.py sendToDB function with error_message = " + str(e)
        print ("Handle Repost of Post = %s success !!!" % iPostId)
                        
    def _processSiglePost(self, iFirstPostId):
        lParams = {}
        lParams['id'] = iFirstPostId
        lParams['count'] = 50
        lParams['access_token'] = self.mPublicToken[1]
        
        print ("Get repost status for repostId = %s" % iFirstPostId)
        self.mRepostStatus = self.fetchUsingAPI(self.mAPI, lParams)
        print ("Get repost status success !!!")
        if type(self.mRepostStatus) == types.ListType and len(self.mRepostStatus) > 0:
            self._sendToDB(iFirstPostId)
                
    def process(self):
        lFilePathName = "logs\\currentPostId.log"
        lSQLStatement = "SELECT (Post_id) FROM POST %s ORDER BY Post_id asc"
        lCurrentPostId = ""
        if os.path.isfile(lFilePathName):
            lFile_Object = open(lFilePathName, 'r')
            try:
                lCurrentPostId = lFile_Object.read()
            finally:
                lFile_Object.close()
        if lCurrentPostId == "":
            lSQLStatement = (lSQLStatement % "")
        else:
            lSQLStatement = (lSQLStatement % ("WHERE Post_id >= " + lCurrentPostId))
        try:
            result = MySqlDBHandle.execSqlStatement(lSQLStatement)
        except Exception, e:
            print "Error in Repost.py get post id function with error_message = " + str(e)     
        
        if type(result) == types.TupleType and len(result) > 0:
            for lIndexId in range(len(result)):
                lSinglePostId = result[lIndexId][0]
                self._processSiglePost(lSinglePostId)
                lFile_object = open(lFilePathName, 'wb')
                try:
                    lFile_object.write(str(lSinglePostId))
                finally:
                    lFile_object.close()
            lFile_object = open(lFilePathName)
            try:
                lFile_object.write("")
            finally:
                lFile_object.close()
            
        